package com.example.bootdemo.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.bootdemo.model.User;
import com.example.bootdemo.service.UserService;
import com.example.bootdemo.utils.QRCodeUtil;
import com.example.bootdemo.utils.R;
import com.example.bootdemo.utils.RandomStringGenerator;
import com.example.bootdemo.utils.model.ListMap;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.cipher.Signer;
import com.wechat.pay.java.service.partnerpayments.jsapi.JsapiService;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Amount;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Payer;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.PrepayResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.*;

@RestController
@RequestMapping(value = "user", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class UserController {

    /**
     * 商户号
     */
    public static String merchantId = "1558490321"; //1558490321
    /**
     * 商户API私钥路径
     */
    public static String privateKeyPath = "WeChartKey/apiclient_key.pem";
    /**
     * 商户证书序列号
     */
    public static String merchantSerialNumber = "6529A2E23F05839E113011F1B64808F168EF2CA3";
    /**
     * 商户APIV3密钥
     */
    public static String apiV3Key = "185FTQ6COEUBN1VIROT5DTIPWMP7U3IH";
    static String appid = "wxd7696c92a7c429c4";  //wxd7696c92a7c429c4 //wx681867c868079126
    static String mchid = "1558490321";
    static String notifyUrl = "http://47.95.199.216:8899/pay/leshua/callBack";
    @Autowired
    @Qualifier("userService1")
    UserService userService;

    @RequestMapping(value = "jsapi", method = RequestMethod.POST)
    public R jsapi(@RequestBody User payInfo) {

        Long chargeId = payInfo.getId();
      /*  ScdCostChargeRegesterEntity charge = this.scdCostChargeRegesterService.getById(chargeId);
        String outTradeNo = charge.getOutTradeNo();
*/
        String outTradeNo = "no_202409263626520001" + chargeId;

        // 使用自动更新平台证书的RSA配置
        // 一个商户号只能初始化一个配置，否则会因为重复的下载任务报错
        Config config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId)
                        .privateKeyFromPath(privateKeyPath)
                        .merchantSerialNumber(merchantSerialNumber)
                        .apiV3Key(apiV3Key)
                        .build();
        JsapiService service = new JsapiService.Builder().config(config).build();
        // request.setXxx(val)设置所需参数，具体参数可见Request定义
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(100);
        request.setAmount(amount);
        request.setSpAppid(appid);
        request.setSpMchid(mchid);
        request.setDescription("测试商品标题");
        request.setNotifyUrl(notifyUrl);
        request.setSubMchid("1598538551");
        request.setOutTradeNo(outTradeNo);
        Payer payer = new Payer();
        payer.setSpOpenid("oQLVc1BPTgV_wFoSbRbf4TWUk_GQ");
        // payer.setSubOpenid("oI652506EOVCZJwjdxbcVart-VZU");

        request.setPayer(payer);
        PrepayResponse response = service.prepay(request);

        System.out.println("-----------");
        System.out.println(JSON.toJSONString(response));
        System.out.println(response.getPrepayId());
        String prepayId = response.getPrepayId();
        long timeStamp = System.currentTimeMillis();
        String nonceStr = RandomStringGenerator.genRandomAlphanumeric(10);
        // 4.根据得到的prepay_id计算paySign 签名
        Map<String, String> sParams = new HashMap<>();
        sParams.put("appId", appid);        //请替换成真实的APPID
        sParams.put("timeStamp", String.valueOf(timeStamp));
        sParams.put("nonceStr", nonceStr);
        sParams.put("package", "prepay_id=" + prepayId);
        sParams.put("signType", "RSA");

        long timestamp = Instant.now().getEpochSecond();
        // String nonceStr = NonceUtil.createNonce(32);
        String packageVal = "prepay_id=" + prepayId;
        String message =
                appid + "\n" + timestamp + "\n" + nonceStr + "\n" + packageVal + "\n";
        // String sign = signer.sign(message).getSign();

        Signer signer1 = config.createSigner();
        String sign = signer1.sign(message).getSign();
        sParams.put("paySign", sign);

        System.out.println(JSON.toJSONString(sParams));
        //    PrepayWithRequestPaymentResponse prepayWithRequestPaymentResponse = prepayWithRequestPayment(prepayId, appid);
        //   System.out.println(prepayWithRequestPaymentResponse);

        //得到 paySign 签名  paySingKey 是商户密匙
        return R.ok(0, sParams);
    }

    @RequestMapping(value = "pageListBigData", method = RequestMethod.GET)
    public R pageListBigData() {
        userService.pageListBigData();
        return R.ok();
    }

    @RequestMapping(value = "pageList", method = RequestMethod.POST)
    public R pageList() {
        List li = new ArrayList<>();

        User user = userService.getById(1);
        return R.ok().put("page", user);
    }

    @RequestMapping(value = "info", method = RequestMethod.GET)
    public R info() {

        User user = userService.getById(1);
        return R.ok().put("page", user);
    }

    @RequestMapping(value = "getById", method = RequestMethod.GET)
    public R getById(@RequestParam String id) {

        User user = userService.getById(id);
        return R.ok().put("page", user);
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public R list() {
        List<User> list = userService.list();

        return R.ok().put("list", list);
    }

    @RequestMapping(value = "listUser", method = RequestMethod.POST)
    public R listUser(@RequestBody Map<String, Object> map) {
        List<User> list = userService.listUser(map);

        return R.ok(list);
    }

    @RequestMapping(value = "listMap", method = RequestMethod.GET)
    public R listMap() {
        List<Map<String, Object>> list = userService.listMaps1();

        return R.ok().put("list", list);
    }

    @RequestMapping(value = "listMap1", method = RequestMethod.POST)
    public R listMap1(@RequestBody ListMap listMap) {

        System.out.println(listMap);
        List<Map<String, Object>> list = userService.listMaps1();

        return R.ok().put("list", list);
    }

    @RequestMapping(value = "listMap2", method = RequestMethod.GET)
    public R listMap2() {
        List<Map<String, Object>> list = userService.listMaps1();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("name", "email", "manager_id", "create_time");
        List<Map<String, Object>> li = userService.listMaps(queryWrapper);

        return R.ok().put("list", list).put("li", li);
    }


    @RequestMapping(value = "encode", method = RequestMethod.GET)
    public R encode() throws Exception {
        String text = "URL";
        String orgName = "中文测试1";
        String remarks = "中文测试2";
        String destPath = new Random().nextInt(99999999) + "user.png";
        //String dirurl=  System.getProperty("user.dir");
        //  System.out.println(dirurl);
        QRCodeUtil.encode(text, null, destPath, true, orgName, remarks);
        return R.ok();
    }
}
